package com.market.service.wx.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.market.bean.*;
import com.market.bean.common.BasePageInfo;
import com.market.bean.common.BaseRespVo;
import com.market.bean.common.CommonData;
import com.market.bean.vo.wx.WxCouponMyListVo;
import com.market.mapper.MarketCartMapper;
import com.market.mapper.MarketCouponMapper;
import com.market.mapper.MarketCouponUserMapper;
import com.market.service.wx.WxCouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Author:WalterChan
 * @Decription:WxCouponServiceImpl
 * @Date Created in 2023-01-02-16:10
 */
@Service
public class WxCouponServiceImpl implements WxCouponService {
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;
    @Autowired
    MarketCartMapper marketCartMapper;

    @Override
    public CommonData<MarketCoupon> list(BasePageInfo info) {
//        获取分页
        PageHelper.startPage(info.getPage(),info.getLimit());
        Date date = new Date();
        MarketCouponExample example= new MarketCouponExample();
        MarketCouponExample.Criteria criteria = example.createCriteria();
        criteria.andIdIsNotNull();

        List<MarketCoupon> list = marketCouponMapper.selectByExample(example);



        PageInfo<MarketCoupon> pageInfo = new PageInfo<>(list);
        return CommonData.data(pageInfo);
    }

    @Override
    public CommonData<WxCouponMyListVo> myList(BasePageInfo info, Integer status,Integer userId) {
//        获取分页
//        PageHelper.startPage(info.getPage(),info.getLimit());
        //        找到endtime<现在的 Date 的列表
        Date date = new Date();

        MarketCouponUserExample example = new MarketCouponUserExample();
        MarketCouponUserExample.Criteria criteria = example.createCriteria();


        criteria.andEndTimeLessThanOrEqualTo(date);
        criteria.andUserIdEqualTo(userId);
        List<MarketCouponUser> expiredList = marketCouponUserMapper.selectByExample(example);
//        update刚才过期的列表，把他们的status=2
        for (MarketCouponUser expiredCoupon : expiredList) {
            expiredCoupon.setUpdateTime(date);
            expiredCoupon.setStatus((short) 2);
            marketCouponUserMapper.updateByPrimaryKey(expiredCoupon);
        }

//        按照status 查找符合规则的List返回
//        0就查不过期的，1就查过期的，2就查使用过的
           List<WxCouponMyListVo>list =marketCouponUserMapper.selectCouponUserCrossCoupon(status,userId);
        for (WxCouponMyListVo wxCouponMyListVo : list) {
            if (Objects.equals(wxCouponMyListVo.getStartTime(),null)){
                wxCouponMyListVo.setStartTime("");
            }
            if (Objects.equals(wxCouponMyListVo.getEndTime(),null)){
                wxCouponMyListVo.setEndTime("");
            }
        }

        PageInfo<WxCouponMyListVo> pageInfo = new PageInfo<>(list);
        return CommonData.data(pageInfo);
    }

    @Override
    public CommonData<WxCouponMyListVo> selectlist(Integer cartId,Integer userId) {
        Date now = new Date();
        List<WxCouponMyListVo>list =marketCouponUserMapper.selectCouponUserCrossCouponByTimeAndStatus(now,userId);

//        查询出购物车的总金额
//        if cartId==0 根据userid去计算总金额
        Double totalPrice;
        if (cartId==0){
             totalPrice=marketCartMapper.sumTotalPriceByUserId(userId);
            System.out.println(totalPrice);
        }else {
            //        if cartId!=0 根据carid去计算总金额
             totalPrice=marketCartMapper.sumTotalPriceByCarId(cartId);
        }
        //遍历list，min< car total price 的，
        //令它的available=true
        for (WxCouponMyListVo wxCouponMyListVo : list) {
            if (wxCouponMyListVo.getMin()<=totalPrice){
                wxCouponMyListVo.setAvailable(true);
            }
        }

        PageInfo<WxCouponMyListVo> pageInfo = new PageInfo<>(list);
        return CommonData.data(pageInfo);
    }

    @Override
    public Integer receive(Integer couponId, Integer userId) {
        Date now = new Date();
        //        查询coupon表获取limit值
//        查询coupo的total值
        MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(couponId);
        int limit = (int) marketCoupon.getLimit();
        Integer total = marketCoupon.getTotal();

        //       查询couponUser表，传入userid和couponId，获取List
//        List.getSize() if(size>=limit)
        MarketCouponUserExample example = new MarketCouponUserExample();
        MarketCouponUserExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andCouponIdEqualTo(couponId);
        List<MarketCouponUser> list = marketCouponUserMapper.selectByExample(example);
//        优惠券已经领取完
        if (list.size()>=total){
            return 740;
        }
//        这个优惠券只能领取一次而且已经领取过
        if (limit==1&&list.size()>0){
            return 740;
        }


//正常领取的情况
            MarketCouponUser marketCouponUser = new MarketCouponUser();
            marketCouponUser.setAddTime(now);
            marketCouponUser.setStatus(marketCoupon.getStatus());
            marketCouponUser.setUpdateTime(now);
            marketCouponUser.setEndTime(marketCoupon.getEndTime());
            marketCouponUser.setCouponId(marketCoupon.getId());
            marketCouponUser.setStartTime(marketCoupon.getStartTime());
            marketCouponUser.setUserId(userId);

            marketCouponUserMapper.insertSelective(marketCouponUser);

            MarketCoupon marketCoupon1 = new MarketCoupon();
            marketCoupon1.setId(couponId);
            marketCoupon1.setUpdateTime(now);
            marketCoupon1.setTotal(total-1);
            marketCouponMapper.updateByPrimaryKeySelective(marketCoupon1);

            return 0;





    }

    @Override
    public BaseRespVo exchange(Integer userId, String code) {
        BaseRespVo<Object> baseRespVo = new BaseRespVo<>();
//        查询数据表校验优惠券是否正确
//        不正确返回        BaseRespVo baseRespVo = BaseRespVo.invalidData("优惠券不正确"); data=742
        MarketCouponExample couponExample = new MarketCouponExample();
        MarketCouponExample.Criteria couponExampleCriteria = couponExample.createCriteria();
        couponExampleCriteria.andCodeEqualTo(code);
        couponExampleCriteria.andDeletedEqualTo(false);
        List<MarketCoupon> marketCouponList = marketCouponMapper.selectByExample(couponExample);
        if (marketCouponList.isEmpty()){
            baseRespVo.setErrno(742);
            baseRespVo.setErrmsg("优惠券不正确");
            return baseRespVo;
        }


//      检查total是否够兑换
        if (marketCouponList.get(0).getTotal()<=0) {
            baseRespVo.setErrno(740);
            baseRespVo.setErrmsg("优惠券已兑换完");
            return baseRespVo;
        }
//                marketCouponList不为空的话获取第一个元素的couponId
        Integer couponId = marketCouponList.get(0).getId();
        int limit =(int) marketCouponList.get(0).getLimit();
//        个人领取达到上限的情况
//        先查userCoupon表，得到这个用户获取了多少张同类的折扣券然后进行判断
        MarketCouponUserExample couponUserExample = new MarketCouponUserExample();
        MarketCouponUserExample.Criteria couponUserExampleCriteria = couponUserExample.createCriteria();
        couponUserExampleCriteria.andUserIdEqualTo(userId);
        couponUserExampleCriteria.andCouponIdEqualTo(couponId);
        List<MarketCouponUser> couponUserList = marketCouponUserMapper.selectByExample(couponUserExample);
        if (!couponUserList.isEmpty()) {
//        如果limit>0 非无限领取的情况&& couponUserList.size>=limt 代表个人已经达到了领取上限了
            if (limit>0&&(couponUserList.size()>=limit)){
                baseRespVo.setErrno(740);
                baseRespVo.setErrmsg("优惠券已兑换完");
                return baseRespVo;
            }

        }
        MarketCoupon marketCoupon=marketCouponList.get(0);

//        可以正常兑换的情况
        Date now = new Date();
        MarketCouponUser marketCouponUser = new MarketCouponUser();
        marketCouponUser.setAddTime(now);
        marketCouponUser.setStatus(marketCoupon.getStatus());
        marketCouponUser.setUpdateTime(now);
        marketCouponUser.setEndTime(marketCoupon.getEndTime());
        marketCouponUser.setCouponId(marketCoupon.getId());
        marketCouponUser.setStartTime(marketCoupon.getStartTime());
        marketCouponUser.setUserId(userId);

        marketCouponUserMapper.insertSelective(marketCouponUser);

        MarketCoupon marketCoupon1 = new MarketCoupon();
        marketCoupon1.setId(couponId);
        marketCoupon1.setUpdateTime(now);
        marketCoupon1.setTotal(marketCoupon.getTotal()-1);
        marketCouponMapper.updateByPrimaryKeySelective(marketCoupon1);

        baseRespVo.setErrno(0);
        baseRespVo.setErrmsg("成功");
        return baseRespVo;

    }


}
